﻿using System.IO;
using System.Text;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using IotClient.Unity;
using IotClient.VM;

namespace IotClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : HandyControl.Controls.Window
    {
        public MainWindow()
        {
            InitializeComponent();
            VM.LogCall = LogCall;
            txtPush.Text = VM.MQTTUnity.AutoPayload();
            Loaded += MainWindow_Loaded;
            Closed += MainWindow_Closed;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (File.Exists("ClientSetting.json"))
                {
                    VM.Setting = ClientSetting.Deserialize(File.ReadAllText("ClientSetting.json"));
                    VM.Setting.ConnentCall = VM.MQTTUnity.ConnentCall;
                }
            }
            catch (Exception ex) { 
            }
        }

        private void MainWindow_Closed(object? sender, EventArgs e)
        {
            VM.Setting.Enable = false;
            File.WriteAllText("ClientSetting.json", VM.Setting.Serialize());
        }

        private void LogCall(string msg, bool newLine)
        {
            if (newLine)
                txtLog.Text += $"\n[{MQTTUnity.GetTime()}]";
            txtLog.Text += msg;
            txtLog.ScrollToEnd();
        }

        private void clear(object sender, RoutedEventArgs e)
        {
            txtLog.Text = "";
        }

        private void push(object sender, RoutedEventArgs e)
        {
            VM.MQTTUnity.Push(txtPush.Text);
        }
    }
}
